//
//  HZOAuthVM.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/19.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SVProgressHUD

class HZOAuthVM: NSObject {
    
    
    //单例对象
    static let sharedVM = HZOAuthVM()
    
    
    //初始化的时候
    override init() {
        
        super.init()
        
        
        //反归档
       model = unarchive()

    }
    
    //定义网络模型对象
    var model:HZOAuthModel?
    
    
    //bool类型来判断是否登入成功了
    var loginEnd:Bool{
        
        //判断是否获取到了token(第一次运行的时候是没有数据的,所以要用?)
        guard let _ =  self.model?.access_token else{
            
            return false
        }
        
        guard let date = self.model?.expirationDate else{
            return false
        }
        
        //如果还没有过期
        if NSDate().compare(date) == .OrderedAscending{
            
            return true
        }
        
        
        
        
       return false
    }
    
    
    


    
    
    // MARK: -  获取access_token
    func giveAccess_token(code:String,finished:(succ:Bool)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let paras = [
            
            "client_id":APP_KEY,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":APP_URL
        ]
        
        //网络 post请求
        HZNetTools.sharedTools.deliveryThing(requestMethod: .Post, urlString: urlString, parameter: paras) { (thing, error) -> () in
            
            
            guard let responstObject = thing else{
                print("获取access_token请求失败")
                
                //失败的闭包
                finished(succ: false)
                
                return
            }
            
            //字典转模型
            let model = HZOAuthModel.init(dict: responstObject as! [String:AnyObject])
            
            //            print(model)
            //获取用户的个人信息
            self.givePersonalInfo(model, finished: finished)
            
            
        }
        
        
    }
    
    // MARK: -  获取用户的个人信息
    private func givePersonalInfo(model:HZOAuthModel,finished:(succ:Bool)->()){
        
        
        //个人信息的请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let paras = [
            
            "access_token" : model.access_token ?? "",
            "uid" : model.uid ?? ""
            
        ]
        
        HZNetTools.sharedTools.deliveryThing(requestMethod: .Get, urlString: urlString, parameter: paras) { (thing, error) -> () in
            
            
            if error != nil{
                
                //网络错误的弹窗
                SVProgressHUD.showErrorWithStatus("网络错误")
                //失败的闭包
                finished(succ: false)
                
                return
            }
            
            guard let requonstObject = thing else{
                
                
                print("个人信息请求错误")
                
                //失败的闭包
                finished(succ: false)
                return
            }
            
            //            print(requonstObject)
            let requonst = requonstObject as! [String: AnyObject]
            
            model.name = (requonst["name"] as! String)
            model.profile_image_url = (requonst["profile_image_url"] as! String)
            
            //赋值,让第一次登陆时有数据
            self.model = model
            //
//                        print(model.name)
//                        print(model.profile_image_url)
            
           
            //归档
            self.archive(model)
            
            // 成功的闭包
            finished(succ: true)
            
        }
        
        
    }
    
    //Swift 的归档
    private func archive(model:HZOAuthModel){
        
        //拼接要保存到的沙盒路径
        let docmString = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("model.archive")
        
        
        
        //把网络数据模型归档
        NSKeyedArchiver.archiveRootObject(model, toFile: docmString)
        
    }
    
      //Swift 的反归档
    private func unarchive()->HZOAuthModel?{
        
        //拼接保存到的沙盒路径
        let docmString = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("model.archive")
        
        //反归档获取数据
        model = (NSKeyedUnarchiver.unarchiveObjectWithFile(docmString) as? HZOAuthModel)
        
        return model
    }

 
    
    
    
    

}
